package com.neusoft.databus.policy.event.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import com.neusoft.databus.common.bean.ResourceBean;
import com.neusoft.databus.policy.enums.EventStatus;
import com.neusoft.databus.policy.event.PolicyEventHandler;
import com.neusoft.databus.policy.model.Event;
import com.neusoft.databus.policy.model.EventAttribute;
import com.neusoft.databus.policy.model.Policy;
import com.neusoft.databus.policy.utils.PolicyUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 业务处理 系统异常事件处理类
 *
 * @author naxiang
 */
@Slf4j
@Component("sysTemEventHandler")
public class SysTemEventHandlerImpl extends PolicyEventHandlerImpl {

    @Override
    public void trigger(ResourceBean resourceBean, Date time, Policy policy,
            final List<Integer> expressionTrueSquence) {
        final String resourceCode = resourceBean.getCode();
        final String key = PolicyUtil.getEventKey(resourceCode, policy.getCode());
        Event event = null;
        try {
            event = this.getEvent(policy, resourceCode);
            final EventAttribute eventAttibute = event.getEventAttribute();
            eventAttibute.setLastTime(time);
            eventAttibute.setContent(this.eventContent(resourceCode, policy.getContentTemplate()));
            // event.setSort(EventSort.SYSTEM);// 策略告警
            event.setStatus(EventStatus.UNFIXED);
            synchronized (this.getLockInstance(resourceCode)) {
                if (!this.cacheService.isInCache(PolicyEventHandler.cacheName,
                        key)) {
                    this.cacheService.put(PolicyEventHandler.cacheName,
                            key, event.getCode());
                } else {
                    event.setCode(String.valueOf(this.cacheService.get(
                            PolicyEventHandler.cacheName, key)));
                }
            }
            this.policyEventBus.post(event);
        } catch (final Exception e) {
            SysTemEventHandlerImpl.log.error("系统异常告警事件,策略code:{},资源code:{},产生异常{}", policy.getCode(), resourceCode,
                    e);
        } finally {
            // 置空大对象,以免内存增长过快
            time = null;
            event = null;
            resourceBean = null;
            policy = null;
        }
    }
}
